package test03;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

public class SendThenReceive {
	public static final byte[] DEST_ADDR = new byte[]{(byte) 158, (byte) 130, (byte) 67, (byte) 216};
	public static final int DEST_PORT = 4505;
	public static final int MAX_PACKET_SIZE = 10;
	
	public static void main(String args[]){
		try {
			//send to DEST_ADDR
			InetAddress destAddr = InetAddress.getByAddress(DEST_ADDR);
			byte[] testBytes = new byte[]{(byte) 1, (byte) 2, (byte) 3, (byte) 99};
			DatagramPacket message = new DatagramPacket(testBytes, testBytes.length, destAddr, DEST_PORT);
			DatagramSocket sock = new DatagramSocket();
			sock.send(message);
			
			//receive
			DatagramPacket packet = new DatagramPacket(new byte[MAX_PACKET_SIZE], MAX_PACKET_SIZE);
	    	sock.receive(packet);
	    	int length = packet.getLength();
	    	byte[] data = packet.getData();
	    	InetAddress sourceAddr = packet.getAddress();
	    	String sourceHostName = sourceAddr.getHostName();
	    	String sourceHostAddr = sourceAddr.getHostAddress();
	    	System.out.println("packet received: ");
	    	System.out.println("---source name: " + sourceHostName);
	    	System.out.println("---source address: " + sourceHostAddr);
	    	System.out.println("---length: " + length);
	    	System.out.print("---data: ");
	    	for(int i=0; i<length; i++){
	    		System.out.print(data[i] + " ");
	    	}
	    	
	    	//close socket
			sock.close();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
